import Flutter
import UIKit
import PPBluetoothKit
import PPCalculateKit

public class LfProductPlugin: NSObject, FlutterPlugin,FlutterStreamHandler {
    var lefuManager:LfManager?
    static let shared:LfProductPlugin = LfProductPlugin()
    var eventSink: FlutterEventSink?
    
    public static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: "lf_product_plugin", binaryMessenger: registrar.messenger())
        let instance = LfProductPlugin.shared
        // let instance = LfProductPlugin()
        registrar.addMethodCallDelegate(instance, channel: channel)
        
        // eventChannel
        let eventChannel = FlutterEventChannel(
            name: "lf_product_plugin_event",
            binaryMessenger: registrar.messenger()
        )
        eventChannel.setStreamHandler(instance)
    }
    
    struct Msg: Codable {
        var code: Int
        var msg: String
        var ppFat: CGFloat?
        var ppBMI: CGFloat?
    }
    
    func formatResult(result: Msg) -> String {
        do {
            let jsonData = try JSONEncoder().encode(result)
            if let jsonString = String(data: jsonData, encoding: .utf8) {
                return jsonString // 输出JSON字符串，例如："{\"name\":\"John Doe\",\"age\":30}"
            }
            return "{\"code\":0,\"msg\":\"calc fail\"}"
        } catch {
            return "{\"code\":0,\"msg\":\"calc fail\"}"
        }
    }
    
    // 监听
    public func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        eventSink = events
        return nil
    }
    
    public func onCancel(withArguments arguments: Any?) -> FlutterError? {
        eventSink = nil
        return nil
    }
    
    
    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        print("iOS rec metod: " + call.method)
        switch call.method {
        case "getPlatformVersion":
            result("iOS " + UIDevice.current.systemVersion)
        case "getHelloWorld":
            result("HelloWorld from iOS")
        case "scan":
            initSDK(["lefu05745512b926075a","knAS3KDlGojeQMvJAyGnDt35jtcj6vzbNuV5vyqOVyw="]);
            getExtensionMessage()
            startService()
            startSearchDevice()
            result(formatResult(result:Msg(code:1,msg:"success scan")))
        case "link":
            guard let args = call.arguments as? [String: Any],
                  let deviceDict = args["device"] as? [String: Any] else {
                print("❌ 参数解析失败，收到的参数: \(call.arguments ?? "无参数")")
                result(FlutterError(code: "INVALID_ARGUMENTS", message: "参数错误", details: nil))
                return
            }
            let deviceMac = deviceDict["deviceMac"] as? String ?? "未知设备"
//            let deviceName = deviceDict["deviceName"] as? String ?? "未知名称"
//            let deviceAccuracyType = deviceDict["deviceAccuracyType"] as? UInt ?? 2
//            let deviceFuncType = deviceDict["deviceFuncType"] as? UInt ?? 73951

            let deviceModel = PPBluetoothAdvDeviceModel()
            deviceModel.deviceMac = deviceDict["deviceMac"] as? String ?? "未知设备"
//            deviceModel.deviceAccuracyType = PPDeviceAccuracyType(rawValue: deviceAccuracyType) ?? .point005
//            deviceModel.deviceName = deviceDict["deviceName"] as? String ?? "未知设备"
//            deviceModel.deviceFuncType = PPDeviceFuncType(rawValue: deviceFuncType)
            
            print(deviceModel)
            startConnDevice(deviceModel)
            result(formatResult(result:Msg(code:1,msg:"success conn")))
        case "calculate4":
            // print(call.arguments as? [String: Any])
            guard let args = call.arguments as? [String: Any],
                  let height = args["height"] as? Int,
                  let weight = args["weight"] as? CGFloat,
                  let heartRate = args["heartRate"] as? Int,
                  let impendance = args["impendance"] as? Int,
                  let age = args["age"] as? Int,
                  let gender = args["gender"] as? Int else {
                result(FlutterError(code: "INVALID_ARGUMENTS", message: "参数错误", details: nil))
                return
            }
            var deviceCalcuteType:PPDeviceCalcuteType?
            let userModel =  PPBluetoothDeviceSettingModel()
            userModel.age = age
            userModel.height = height
            userModel.gender = PPDeviceGenderType.init(rawValue: UInt(0))!
            userModel.isAthleteMode = false //运动员模式
            userModel.isPregnantMode = false //怀孕模式
            var fatModel:PPBodyFatModel!
            fatModel = PPBodyFatModel(userModel: userModel,
                                      deviceCalcuteType: PPDeviceCalcuteType.direct,
                                      deviceMac: "c1:c1:c1:c1",
                                      weight: CGFloat(weight),
                                      heartRate: heartRate,
                                      andImpedance: impendance,
                                      footLen: 0)
            result(formatResult(result:Msg(code:1,msg:"success",ppFat: fatModel.ppFat,ppBMI: fatModel.ppBMI)))
            
            
        case "calculate8":
            print("calculate8 run");
            print(call.arguments as? [String: Any]);
            guard let args = call.arguments as? [String: Any],
                  let height = args["height"] as? Int,
                  let weight = args["weight"] as? CGFloat,
                  let heartRate = args["heartRate"] as? Int,
                  let z20KhzLeftArmEnCode = args["z20KhzLeftArmEnCode"] as? Int,
                  let z20KhzRightArmEnCode = args["z20KhzRightArmEnCode"] as? Int,
                  let z20KhzLeftLegEnCode = args["z20KhzLeftLegEnCode"] as? Int,
                  let z20KhzRightLegEnCode = args["z20KhzRightLegEnCode"] as? Int,
                  let z20KhzTrunkEnCode = args["z20KhzTrunkEnCode"] as? Int,
                  let z100KhzLeftArmEnCode = args["z100KhzLeftArmEnCode"] as? Int,
                  let z100KhzRightArmEnCode = args["z100KhzRightArmEnCode"] as? Int,
                  let z100KhzLeftLegEnCode = args["z100KhzLeftLegEnCode"] as? Int,
                  let z100KhzRightLegEnCode = args["z100KhzRightLegEnCode"] as? Int,
                  let z100KhzTrunkEnCode = args["z100KhzTrunkEnCode"] as? Int,
                  let age = args["age"] as? Int,
                  let gender = args["gender"] as? Int else {
                print("❌ 参数解析失败，收到的参数: \(call.arguments ?? "无参数")")
                result(FlutterError(code: "INVALID_ARGUMENTS", message: "参数错误", details: nil))
                return
            }
            
            var deviceCalcuteType:PPDeviceCalcuteType?
            let userModel =  PPBluetoothDeviceSettingModel()
            userModel.age = age
            userModel.height = height
            userModel.gender = PPDeviceGenderType.init(rawValue: UInt(0))!
            userModel.isAthleteMode = false //运动员模式
            userModel.isPregnantMode = false //怀孕模式
            
            print(PPDeviceCalcuteType.alternate8)
            var fatModel:PPBodyFatModel!
            fatModel  = PPBodyFatModel(userModel: userModel,
                                       deviceMac: "",
                                       weight: CGFloat(weight),
                                       heartRate: heartRate,
                                       deviceCalcuteType: .alternate8,
                                       z20KhzLeftArmEnCode: z20KhzLeftArmEnCode,
                                       z20KhzRightArmEnCode: z20KhzRightArmEnCode,
                                       z20KhzLeftLegEnCode: z20KhzLeftLegEnCode,
                                       z20KhzRightLegEnCode: z20KhzRightLegEnCode,
                                       z20KhzTrunkEnCode: z20KhzTrunkEnCode,
                                       z100KhzLeftArmEnCode: z100KhzLeftArmEnCode,
                                       z100KhzRightArmEnCode: z100KhzRightArmEnCode,
                                       z100KhzLeftLegEnCode: z100KhzLeftLegEnCode,
                                       z100KhzRightLegEnCode: z100KhzRightLegEnCode,
                                       z100KhzTrunkEnCode: z100KhzTrunkEnCode)
            result(formatResult(result:Msg(code:1,msg:"success",ppFat: fatModel.ppFat,ppBMI: fatModel.ppBMI)))
            
        default:
            result(FlutterMethodNotImplemented)
        }
    }
}

